// DeepSeek API 代理服务器
// 运行方式: node proxy-server.js

const http = require('http');
const https = require('https');

const DEEPSEEK_API_KEY = 'sk-1c2957f7804a4dc4bde7756acfcaec86';
const PORT = 3000;

const server = http.createServer((req, res) => {
    // 设置CORS头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

    // 处理OPTIONS预检请求
    if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
    }

    // 只处理POST请求到/api/chat
    if (req.method === 'POST' && req.url === '/api/chat') {
        let body = '';

        req.on('data', chunk => {
            body += chunk.toString();
        });

        req.on('end', () => {
            try {
                const requestData = JSON.parse(body);

                // 准备发送到DeepSeek的数据
                const deepseekData = JSON.stringify({
                    model: 'deepseek-chat',
                    messages: requestData.messages,
                    max_tokens: requestData.max_tokens || 200,
                    temperature: requestData.temperature || 0.8,
                    stream: false
                });

                // 调用DeepSeek API
                const options = {
                    hostname: 'api.deepseek.com',
                    path: '/chat/completions',
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,
                        'Content-Length': Buffer.byteLength(deepseekData)
                    }
                };

                const apiReq = https.request(options, (apiRes) => {
                    let responseData = '';

                    apiRes.on('data', chunk => {
                        responseData += chunk;
                    });

                    apiRes.on('end', () => {
                        res.writeHead(apiRes.statusCode, { 'Content-Type': 'application/json' });
                        res.end(responseData);
                    });
                });

                apiReq.on('error', (error) => {
                    console.error('DeepSeek API错误:', error);
                    res.writeHead(500, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ 
                        error: 'API调用失败',
                        message: error.message 
                    }));
                });

                apiReq.write(deepseekData);
                apiReq.end();

            } catch (error) {
                console.error('请求处理错误:', error);
                res.writeHead(400, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ error: '请求格式错误' }));
            }
        });
    } else {
        res.writeHead(404);
        res.end('Not Found');
    }
});

server.listen(PORT, () => {
    console.log(`🚀 DeepSeek代理服务器运行在 http://localhost:${PORT}`);
    console.log(`📡 前端请求地址: http://localhost:${PORT}/api/chat`);
});
